import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, message, Tag, Popconfirm} from 'antd'
import {PlusOutlined, ArrowDownOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {
	getTableList,
	deleteApply,
	requisitionImport,
	dictByCode,
	contractAuditFlow,
} from '@/service/purchase/apply'
import {getOnlydept, processRecordSave} from '@/service/common/index'
import {translateDataToTree} from '@/utils/common/index'
import 'moment/locale/zh-cn'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {
	getIsProcessOpen,
	getSupplierBaseExcelList,
} from '@/service/purchase/initiation'
import {formatDate} from '@/utils/common/dateFilter'
import {downloadDocumentUrl} from '@/service/common/download'
import {auditStatus} from '../dict'

interface DataType {
	instanceId: string
	createUser: any
	auditStatus: string
	isAudit: number
	requisitionNo: string
	supplierName: string
	belongCompany: string
	serviceType: string
	number: string
	contacts: string
	fanwei: string
	status: string
	date: string
	id: string
	applyTime?: string
	requisitionOrgname?: string
	requisitionCityname?: string
}

const formItemLayout = {
	labelCol: {flex: '110px'},
	wrapperCol: {flex: '1'},
}

const admittance = (props: any) => {
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [deptList, setDeptList] = useState([])
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [requisitionTypeList, setRequisitionTypeList] = useState<any[]>([])
	const [processOpen, setProcessOpen] = useState<number>(0)

	// 初始化-流程是否激活
	const getIsProcessOpenFun = () => {
		getIsProcessOpen({businessType: 2})
			.then((res: any) => {
				if (res?.success) {
					setProcessOpen(() => res?.data)
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	// 初始化-采购类目
	const onDictByCodeFun = () => {
		dictByCode('purchase_requisition_type')
			.then((res: any) => {
				if (res?.success) {
					setRequisitionTypeList(() => res?.data)
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	// 初始化-需求部门数据
	const getOnlydeptFun = () => {
		getOnlydept({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setDeptList(() => list as any)
			}
		})
	}
	useEffect(() => {
		onDictByCodeFun()
		getOnlydeptFun()
		getIsProcessOpenFun()
	}, [props?.user?.orgId])

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(() => res?.data?.records)
					setTotal(() => res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 导出事件
	const onExportClick = () => {
		downloadDocumentUrl({
			resourceId: '142',
			queryDesc: '采购申请导出,resourceId:142',
			queryParam: searchData,
		})
	}

	// 删除事件
	const onDeleteFun = (ids: string) => {
		deleteApply({ids})
			.then((res) => {
				if (res.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 流程作废
	const onAuditFlowFun = (record: {id: string; instanceId: string}) => {
		contractAuditFlow({
			businessId: record?.id,
			instanceId: record?.instanceId,
			pass: '3',
			message: JSON.stringify({
				userName: props?.user?.userName,
				message: '已作废',
			}),
		})
			.then((res: {msg: string; success: boolean}) => {
				if (res?.success) {
					processRecordSave({
						bizType: 2,
						bizNo: record?.id,
						processId: record?.instanceId,
					})
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '采购申请单号',
			dataIndex: 'requisitionNo',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '审核状态',
			dataIndex: 'auditStatus',
			align: 'center',
			width: 150,
			render: (text: number, record: any) => (
				<>
					{auditStatus?.map((item: {key: number; label: string}) => {
						if (item?.key === Number(text)) {
							return (
								<Tag color="processing" key={record?.id}>
									{item?.label}
								</Tag>
							)
						}
						return null
					})}
				</>
			),
		},
		{
			title: '立项编号',
			dataIndex: 'applycostNo',
			align: 'center',
			width: 350,
			ellipsis: true,
			render: (text: any, record: any) => (
				<>
					{text ? (
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/purchase/initiation/view',
									query: {
										id: record?.applycostId,
										goPath: props.location.pathname,
									},
								})
							}}>
							{text}
						</Button>
					) : (
						'--'
					)}
				</>
			),
		},
		{
			title: '需求组织',
			dataIndex: 'requisitionOrgname',
			width: 250,
			align: 'center',
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '需求城市',
			dataIndex: 'requisitionCityname',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: number, record: any) => (
				<>
					<span>
						{record.requisitionProvincename}/{text}
					</span>
				</>
			),
		},
		{
			title: '需求部门',
			dataIndex: 'requisitionDeptname',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '采购类目',
			dataIndex: 'requisitionName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '采购描述',
			dataIndex: 'requisitionDesc',
			align: 'center',
			width: 150,
			render: (text) => (
				<div className="ellipsis" title={text}>
					{text || '--'}
				</div>
			),
		},
		{
			title: '供应商',
			dataIndex: 'supplierName',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '申请时间',
			dataIndex: 'applyTime',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text) => (
				<span>
					{' '}
					{processOpen === 1
						? moment(text).format('YYYY-MM-DD HH:mm:ss')
						: moment(text).format('YYYY-MM-DD')}
				</span>
			),
		},
		{
			title: '申请人',
			dataIndex: 'applicantName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record) => (
				<div>
					<Permissions permissionID="amc_assetCenter_purchase_apply_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/purchase/apply/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{record?.isAudit === 1 && record?.auditStatus !== '4' ? (
						<Permissions permissionID="amc_assetCenter_purchase_apply_process">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname: '/purchase/apply/process',
										query: {
											id: record.id,
										},
									})
								}}>
								审核
							</Button>
						</Permissions>
					) : null}
					{String(record?.createUser) ===
					String(props?.user?.userId) ? (
						<>
							{record?.auditStatus === '3' ? (
								<Permissions permissionID="amc_assetCenter_purchase_apply_cancel">
									<Popconfirm
										placement="topLeft"
										title="你确定要作废这条数据吗？"
										onConfirm={() => onAuditFlowFun(record)}
										okText="确定"
										cancelText="取消">
										<Button type="link" size="small">
											作废
										</Button>
									</Popconfirm>
								</Permissions>
							) : null}
							{record?.auditStatus === '9' ? (
								<>
									<Permissions permissionID="amc_assetCenter_purchase_apply_edit">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/purchase/apply/edit',
													query: {
														id: record.id,
													},
												})
											}}>
											编辑
										</Button>
									</Permissions>
								</>
							) : null}
							{record?.auditStatus === '4' ? (
								<>
									<Permissions permissionID="amc_assetCenter_purchase_apply_reissue">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/purchase/apply/edit',
													query: {
														id: record.id,
													},
												})
											}}>
											再次发起
										</Button>
									</Permissions>
								</>
							) : null}
							{record?.auditStatus === '9' ||
							record?.auditStatus === '4' ? (
								<Permissions permissionID="amc_assetCenter_purchase_apply_delete">
									<Popconfirm
										placement="topLeft"
										title="你确定要删除这条数据吗？"
										onConfirm={() => onDeleteFun(record.id)}
										okText="确定"
										cancelText="取消">
										<Button type="link" size="small">
											删除
										</Button>
									</Popconfirm>
								</Permissions>
							) : null}
						</>
					) : null}
				</div>
			),
		},
	]

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])

	// 搜索
	const onFinish = (values: any) => {
		const applyTimeStart = formatDate(values?.applyTime?.[0], 'YYYY-MM-DD')
		const applyTimeEnd = formatDate(values?.applyTime?.[1], 'YYYY-MM-DD')
		const search = {
			...values,
			applyTimeStart,
			applyTimeEnd,
		}
		delete search?.applyTime
		setSearchData(search)
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						label: '采购申请单号',
						name: 'requisitionNo',
						key: 'requisitionNo',
					},
					{
						type: 'input',
						label: '立项编号',
						name: 'applycostNo',
						key: 'applycostNo',
					},
					{
						type: 'input',
						label: '需求组织',
						name: 'requisitionOrgname',
						key: 'requisitionOrgname',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'input',
						label: '需求城市',
						name: 'requisitionCityname',
						key: 'requisitionCityname',
					},
					{
						type: 'treeSelect',
						label: '需求部门',
						name: 'requisitionDeptid',
						key: 'requisitionDeptid',
						keys: 'id',
						title: 'name',
						treeData: [...deptList],
					},
					{
						type: 'treeSelect',
						key: 'requisitionType',
						name: 'requisitionType',
						label: '采购类目',
						keys: 'key',
						title: 'value',
						children: 'childList',
						treeData: [...requisitionTypeList],
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'input',
						label: '供应商',
						name: 'supplierName',
						key: 'supplierName',
					},
					{
						type: 'select',
						key: 'auditStatus',
						name: 'auditStatus',
						label: '审核状态',
						keys: 'key',
						title: 'label',
						items: [...auditStatus],
					},
					{
						type: 'dateRange',
						key: 'applyTime',
						name: 'applyTime',
						label: '申请日期',
					},
				],
			},
		]
		setFormData(formItems)
	}, [deptList, requisitionTypeList])

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '需求组织',
			dataIndex: 'requisitionOrgname',
			align: 'center',
		},
		{
			title: '需求城市',
			dataIndex: 'requisitionCityname',
			align: 'center',
		},
		{
			title: '需求部门',
			dataIndex: 'requisitionDeptname',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'resultMsg',
			align: 'center',
		},
	]

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_purchase_apply_add">
						<Button
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push('/purchase/apply/add')
							}}>
							新增
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_purchase_apply_import">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_import"
							onClick={() => setIsUploadModalOpen(true)}>
							导入
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_purchase_apply_export">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_warning"
							onClick={onExportClick}>
							导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					scroll={{y: 480}}
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={requisitionImport}
				onTableList={getSupplierBaseExcelList}
				getListData={onListFun}
				fileNmae="file"
				uploadFileUrl={`${modalApi.purchase}/shopec-purchase-requisition/requisition/import/view`}
				columns={errorColumns}
				sourceId={18}
				templateType="采购申请"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(admittance)
